/*
 * @(#)XML_IO.java        0.1 09/04/29
 * @version 	0.1 29 Apr 2009
 * @author 	Nguyen Thang Huy
 * 
 * Doc va luu mot phien lam viec duoi dang XML
 */


package XML_IO;

import java.util.*;
import java.io.*;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

import Data.*;

public class XML_IO {
	/*
	 * Luu thong tin cua  1 phien lam viec ra file XML
	 */
	public void save(LinkedList<Data.Class> classes, LinkedList<Line> lines, File file) {
		DocumentBuilder docbuilder;
    	DocumentBuilderFactory docbuilderfactory = DocumentBuilderFactory.newInstance();
    	docbuilderfactory.setIgnoringElementContentWhitespace(true);
    	try {
    		docbuilder = docbuilderfactory.newDocumentBuilder();
    	} catch (ParserConfigurationException e){
    		System.out.println("wrong parser configuration: "+e.getMessage());
    		return;
    	}
    	Document doc = docbuilder.newDocument();
    	Element root = doc.createElement("JCG");
    	root.setAttribute("type", "UML");
    	doc.appendChild(root);
    	
    	// Luu cac class
    	Element classesElement = doc.createElement("classes");
    	root.appendChild(classesElement);
    	for (int i = 0; i < classes.size(); i++) {
    		classesElement.appendChild(classes.get(i).toXml(doc));
    	}
    	
    	// Luu cac Line
    	Element linesElement = doc.createElement("lines");
    	root.appendChild(linesElement);
    	for (int i = 0; i < lines.size(); i++) {
    		linesElement.appendChild(lines.get(i).toXml(doc));
    	}
    	
    	TransformerFactory transformerFactory = TransformerFactory.newInstance();
    	Transformer transformer = null;
    	try {
    		transformer = transformerFactory.newTransformer();    		
    	} catch (Exception e) {
    		
    	}
    	DOMSource source = new DOMSource(doc);
        //File file = new File(optionsFileName+"a");
        StreamResult result =  new StreamResult(file);
        try {
        	transformer.transform(source, result);
        } catch (Exception e) {
        	
        }
	}
	
	// Mo 1 phiem lam viec da luu trong file JCG
	public void open(LinkedList<Data.Class> classes, LinkedList<Shape> shapes, LinkedList<SimpleLine> lines, File file) {
		Document doc = parseFile(file);
		Node root = doc.getDocumentElement();
		NodeList children = root.getChildNodes();
		for (int i = 0; i < children.getLength(); i++) {
			Node child = children.item(i);
			if (child.getNodeType() == Node.ELEMENT_NODE) {
				//Doc danh sach cac class
				if (child.getNodeName().equals("classes")) {
					NodeList tmp = child.getChildNodes();
					for (int j = 0; j < tmp.getLength(); j++) {
						if (tmp.item(j).getNodeType() == Node.ELEMENT_NODE) {
							Data.Class c = new Data.Class(tmp.item(j));
							classes.addLast(c);
							Shape s = new Shape(tmp.item(j));
							shapes.addLast(s);
						}
					}
				}
			
				// Danh sach cac quan he
				if (child.getNodeName().equals("lines")) {
					NodeList tmp = child.getChildNodes();
					for (int j = 0; j < tmp.getLength(); j++) {
						if (tmp.item(j).getNodeType() == Node.ELEMENT_NODE) {
							SimpleLine l = new SimpleLine(tmp.item(j));
							lines.addLast(l);
						}
					}
				}
			}
		}
	}
	
	
	public static String getElementValue(Node elem)
	{
		Node kid;
		if (elem != null )
		{
			if (elem.hasChildNodes())
			{
				for (kid = elem.getFirstChild();kid!=null;kid=kid.getNextSibling())
				{
					if (kid.getNodeType()==Node.TEXT_NODE)
					{
						return kid.getNodeValue();
					}
				}
			}
		}
		return "";
	}
	
    private Document parseFile (File file) {
    	DocumentBuilder docbuilder;
    	Document doc = null;
    	DocumentBuilderFactory docbuilderfactory = DocumentBuilderFactory.newInstance();
    	docbuilderfactory.setIgnoringElementContentWhitespace(true);
    	try {
    		docbuilder = docbuilderfactory.newDocumentBuilder();
    	} catch (ParserConfigurationException e){
    		System.out.println("wrong parser configuration: "+e.getMessage());
    		return null;
    	}
    	try {
    		doc = docbuilder.parse(file);
    	} catch (SAXException e){
    		System.out.println("wrong XML file structure: "+e.getMessage());
    		return null;
    	}catch (IOException e){
    		System.out.println("Could not read source file: "+e.getMessage());
    	}
    	System.out.println("parse XML file");
    	return doc;
    }
}
